from snippets.models import Snippet
from snippets.serializers import SnippetSerializer
from django.contrib.auth.models import User
from .serializers import UserSerializer

from snippets.permissions import IsOwnerOrReadOnly
from rest_framework import renderers

from rest_framework.decorators import api_view
from rest_framework.reverse import reverse
from rest_framework import viewsets


from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework import permissions


class SnippetViewSet(viewsets.ModelViewSet):
    """
    这个视图集自动提供“列表”、“创建”、“检索”,“更新”和“删除”操作。
    （牛逼！一个视图覆盖了增、删、改、查和列表！！！）

    此外，我们还提供额外的“高亮”动作。
    """
    queryset = Snippet.objects.all()
    serializer_class = SnippetSerializer
    permission_classes = [permissions.IsAuthenticatedOrReadOnly,
                          IsOwnerOrReadOnly]

    @action(detail=True, renderer_classes=[renderers.StaticHTMLRenderer])
    def highlight(self, request, *args, **kwargs):
        snippet = self.get_object()
        return Response(snippet.highlighted)

    def perform_create(self, serializer):
        serializer.save(owner=self.request.user)


class UserViewSet(viewsets.ReadOnlyModelViewSet):
    """
    此视集自动提供“列表”和“检索”操作。
    """
    queryset = User.objects.all()
    serializer_class = UserSerializer


@api_view(['GET'])
def api_root(request, format=None):
    return Response({
        'users': reverse('user-list', request=request, format=format),
        'snippets': reverse('snippet-list', request=request, format=format)
    })
